import requests
from utils.data_loader import CoinDataset
import time
import threading

class CoinImageDownloader:
    def __init__(self, base_url: str, offset: int, limit: int, max_offset: int):
        self.base_url = base_url
        self.offset = offset
        self.limit = limit
        self.max_offset = max_offset
        self.coin_dataset = CoinDataset(
            api_url=base_url,
            title="title",
            page_size=10,
            offset=0,
            max_offset=max_offset
        )
        
    def start(self):
        while self.offset < self.max_offset:
            success = self.load_data()
            if not success:
                print(f"下载失败，等待5秒后重试...")
                time.sleep(5)  # 添加延迟，避免请求过于频繁
                continue

    def load_data(self):
        params = {
            'title': 'yuan coin',  # 添加必要的参数
            'offset': self.offset,
            'limit': self.limit
        }

        try:
            print(f"正在下载 offset: {self.offset}, limit: {self.limit}")
            response = requests.post(self.base_url, json=params)
            if response.status_code == 200:
                response_data = response.json()
                if response_data['code'] == 1:
                    new_data = response_data['data']
                    if new_data:
                        for item in new_data:
                            try:
                                item_id = str(item['id'])  # 确保 id 是字符串
                                front_image_url = item['frontImage']
                                back_image_url = item['backImage']
                                
                                # 下载图片
                                front_result = self.coin_dataset.download_image(front_image_url, item_id)
                                back_result = self.coin_dataset.download_image(back_image_url, item_id)
                                
                                if front_result is not None and back_result is not None:
                                    print(f"成功下载硬币 {item_id} 的图片")
                                else:
                                    print(f"硬币 {item_id} 的图片下载失败")
                                
                            except Exception as e:
                                print(f"处理硬币 {item_id} 时出错: {e}")
                                continue
                            
                        self.offset += len(new_data)
                        print(f"当前进度: {self.offset}/{self.max_offset}")
                        return True
                    else:
                        print("没有更多数据了")
                        return False
                else:
                    print(f"获取数据失败: {response_data['msg']}")
                    return False
            else:
                print(f"无法获取数据，状态码: {response.status_code}")
                return False
        except Exception as e:
            print(f"加载数据时出错: {e}")
            return False


if __name__ == "__main__":
    # 创建线程列表
    threads = []
    # 启动多个线程
    start_offset = 100000
    end_offset = 210000
    thread_num = 60
    offset = (end_offset - start_offset) // thread_num  # 计算每个线程的偏移量
    
    for i in range(thread_num):
        current_start_offset = start_offset + i * offset
        current_end_offset = start_offset + (i + 1) * offset
        print(f"开始下载 offset: {current_start_offset}, 结束 offset: {current_end_offset}")
        downloader = CoinImageDownloader(
            base_url="http://154.91.32.174:80/api/coinListPage",
            offset=current_start_offset,
            limit=10,
            max_offset=current_end_offset
        )
        thread = threading.Thread(target=downloader.start)
        threads.append(thread)
        thread.start()  # 启动线程
    # 等待所有线程完成
    for thread in threads:
        thread.join()  # 等待线程结束
    print("所有线程已完成")